package com.zprmb.udzt;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zprmb.udzt.gesture.GestureEditActivity;
import com.zprmb.udzt.http.AjaxParams;
import com.zprmb.udzt.util.BitmapUtils;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.LogUtils;
import com.zprmb.udzt.util.Regular;
import com.zprmb.udzt.util.TimeCount;
import com.zprmb.udzt.util.ToastUtil;
import com.zprmb.udzt.util.VolleryUtil;
import com.zprmb.udzt.view.LoadingDialog;
import com.zprmb.udzt.vo.AuthFailureError;
import com.zprmb.udzt.vo.Request.Method;
import com.zprmb.udzt.vo.RequestQueue;
import com.zprmb.udzt.vo.Response;
import com.zprmb.udzt.vo.VolleyError;
import com.zprmb.udzt.vo.toolbox.HttpClientStack;
import com.zprmb.udzt.vo.toolbox.HttpStack;
import com.zprmb.udzt.vo.toolbox.ImageRequest;
import com.zprmb.udzt.vo.toolbox.JsonObjectRequest;
import com.zprmb.udzt.vo.toolbox.Volley;

/**
 * 短信登录
 *
 * @author shenshao
 */
public class Message_Login extends BaseActivity implements OnClickListener {
    private TextView tv_user_phone;
    private ImageView img_back, img_captcha;
    private RequestQueue mQueue;
    private Button btn_send_mes, btn_login;
    private String csrf;
    private TextView btn_register;
    private EditText et_imgCaptcha, et_login_code;
    String mobile = "";
    private int who;
    private LoadingDialog dialog;
    private TimeCount timeCount;
    private RelativeLayout rl_back;
    //	private ImageView img_reg_bg;
    private TextView tv_voice_code;
    private TextView tv_comment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.message_login);
        BbtApplication.getInstance().addActvity(this);
        setTitle("短信快捷登录", this);
        dialog = new LoadingDialog(this);
        DefaultHttpClient httpclient = new DefaultHttpClient();
        CookieStore cookieStore = new BasicCookieStore();
        httpclient.setCookieStore(cookieStore);
        HttpStack httpStack = new HttpClientStack(httpclient);
        mQueue = Volley.newRequestQueue(this, httpStack);
        tv_comment = (TextView) findViewById(R.id.tv_comment);
        btn_register = (TextView) findViewById(R.id.btn_register);
//		img_reg_bg = (ImageView) findViewById(R.id.img_bg);
        tv_user_phone = (TextView) findViewById(R.id.user_phone);
        img_back = (ImageView) findViewById(R.id.img_back);
        et_login_code = (EditText) findViewById(R.id.login_codes);
        img_captcha = (ImageView) findViewById(R.id.img_captch);
        et_imgCaptcha = (EditText) findViewById(R.id.img_codes);
        btn_login = (Button) findViewById(R.id.btn_login);
        btn_send_mes = (Button) findViewById(R.id.btn_send_mes);
        rl_back = (RelativeLayout) findViewById(R.id.rl_back);
        tv_voice_code = (TextView) findViewById(R.id.tv_voice_code);
        tv_voice_code.setText(Html.fromHtml("收不到短信？点击获取"
                + "<font color='#00aaee'>语音验证码</font>"));
        tv_voice_code.setOnClickListener(this);
        btn_register.setOnClickListener(this);
        rl_back.setOnClickListener(this);
        img_captcha.setOnClickListener(this);
        who = getIntent().getIntExtra("who", 0);
        img_back.setOnClickListener(this);
        timeCount = new TimeCount(60000, 100, btn_send_mes, tv_voice_code);

        tv_user_phone.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                if (Regular.isMobileNO(s.toString())) {
                    btn_send_mes.setVisibility(View.VISIBLE);
                    tv_voice_code.setVisibility(View.VISIBLE);
                } else {
                    btn_send_mes.setVisibility(View.GONE);
                    tv_voice_code.setVisibility(View.GONE);
                }
            }
        });
        if (getIntent().getStringExtra("user_phone").equals("")) {

            mobile = "";
        } else {
            mobile = getIntent().getStringExtra("user_phone");
        }

//		img_reg_bg.setImageBitmap(BitmapUtils.readBitMap(this,
//				R.drawable.v6_login_bg));
        tv_user_phone.setText(mobile);
        if (Regular.isMobileNO(tv_user_phone.getText().toString())) {
            btn_send_mes.setVisibility(View.VISIBLE);
            tv_voice_code.setVisibility(View.VISIBLE);
        } else {
            btn_send_mes.setVisibility(View.GONE);
            tv_voice_code.setVisibility(View.GONE);
        }
        btn_login.setOnClickListener(this);
        btn_send_mes.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        initcaptcha();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        BbtApplication.getInstance().removeActvity(this);
    }

    private void showDialog() {
        if (dialog.isShowing() == false & !Message_Login.this.isFinishing()) {
            dialog.show();
        }
    }

    private void dissmissDialog() {
        if (dialog != null & !Message_Login.this.isFinishing()) {
            dialog.dismiss();
        }
    }

    private void initcaptcha() {
        // TODO Auto-generated method stub
        ImageRequest imageRequest = new ImageRequest(Constant.URL
                + "/captcha.png", new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                img_captcha.setImageBitmap(response);
            }
        }, 0, 0, Config.RGB_565, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                img_captcha.setImageResource(R.drawable.bbt_bg);
            }
        });
        mQueue.add(imageRequest);

    }

    private void initData(final int approach) {
        // 这个接口返回的请求头里有3个参数，，前两个暂时写死！
        VolleryUtil vollery = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
                try {

                    if (jsonObject.optInt("success") == 1) {
                        csrf = jsonObject.getJSONObject("data").optString(
                                "csrf");
                        initmessage(approach);
                    } else {

                        Toast.makeText(Message_Login.this,
                                jsonObject.optString("comment"), 0).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub

            }
        };
        vollery.setHeaders("appId", "bbt3.0:android");
        vollery.setHeaders("appSecret", "RH89xcYh");
        vollery.setHeaders("appVersion", getAppVersion());
        vollery.setRequestMethod(1);

        vollery.execute(this, Constant.URL + "api/csrf", "");
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent intent = null;
        switch (v.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.btn_send_mes:
                if (et_imgCaptcha.getText().toString().equals("")) {
                    Toast.makeText(Message_Login.this, "请输入图形验证码！", 2000).show();
                    return;

                }
                initData(0);

                break;
            case R.id.img_captch:
                initcaptcha();
                break;
            case R.id.btn_login:
                if (et_imgCaptcha.getText().toString().equals("")) {
                    Toast.makeText(Message_Login.this, "请输入图形验证码！", 2000).show();
                    return;

                }
                if (et_login_code.getText().toString().equals("")) {
                    Toast.makeText(Message_Login.this, "请输入短信验证码！", 2000).show();
                    return;

                }
                btn_login.setEnabled(false);
                btn_login.setBackgroundResource(R.drawable.btn_unclick);
                login();
                break;
            case R.id.rl_back:
                finish();
                break;
            case R.id.btn_register:
                intent = new Intent(Message_Login.this, V6RegisterActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.tv_voice_code:
                initData(1);
                break;
        }

    }

    private void changeCommentStatus(int status, String comment) {
        if (status == 1) {
            if (tv_comment.getVisibility() == View.GONE) {
                tv_comment.setVisibility(View.VISIBLE);
                tv_comment.setText(comment);
            }
        } else {
            if (tv_comment.getVisibility() == View.VISIBLE) {
                tv_comment.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        if (tv_comment != null) {

            if (tv_comment.getVisibility() == View.VISIBLE) {
                tv_comment.setVisibility(View.GONE);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private void login() {
        // TODO Auto-generated method stub
        AjaxParams params = new AjaxParams();
        params.put("loginName", tv_user_phone.getText().toString());
        params.put("mobileCaptcha", et_login_code.getText().toString());
        params.put("appVersion", getAppVersion());
        params.put("loginType", "SMS_QUICK");

        VolleryUtil volleryUtil = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
                LogUtils.e(Message_Login.this, "短信登录" + jsonObject.toString());
                if (jsonObject.optInt("success") == 1) {
                    btn_login.setEnabled(true);
                    btn_login.setBackgroundResource(R.drawable.v6button);
                    JSONObject json1 = jsonObject.optJSONObject("data");
                    Editor editor = getShare().edit();
                    editor.putString("token", json1.optString("token"));
                    editor.putString("userId", json1.optString("userId"));
                    editor.putString("photoUrl", json1.optString("photoUrl"));
                    editor.putString("mobile", json1.optString("mobile"));
                    editor.putString("usercode", json1.optString("userCode"));
                    editor.putString("loginName",
                            getIntent().getStringExtra("user_phone"));
                    editor.commit();
                    Toast.makeText(Message_Login.this,
                            jsonObject.optString("comment"), 0).show();
                    if (who == 1) {
                        Message_Login.this.finish();
                        return;
                    }

                    // if (who==3) {
                    // Intent intent = new
                    // Intent(Message_Login.this,GestureEditActivity.class);//MainActivity
                    // intent.putExtra("where", 1);
                    // startActivity(intent);
                    // Message_Login.this.finish();
                    // return;
                    // }

                    if (getShare().getString(getMobile(), "").equals("")) {
                        Intent intent = new Intent(Message_Login.this,
                                GestureEditActivity.class);// MainActivity
                        intent.putExtra("towhere", "main");
                        intent.putExtra("from", "login");
                        startActivity(intent);
                        Message_Login.this.finish();
                        return;
                    }
                    Intent intent = new Intent(Message_Login.this,
                            MainActivity.class);
                    // MainActivity
                    // if(getIntent().getIntExtra("towhere", 0)==1){
                    // intent.putExtra("tab", 1);
                    // }
                    // if(getIntent().getIntExtra("towhere", 0)==2){
                    // intent.putExtra("tab", 2);
                    // }
                    startActivity(intent);

                    Message_Login.this.finish();
                } else {
                    btn_login.setEnabled(true);
                    btn_login.setBackgroundResource(R.drawable.v6button);
                    changeCommentStatus(1, jsonObject.optString("comment"));

                }
            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub
                btn_login.setEnabled(true);
                btn_login.setBackgroundResource(R.drawable.v6button);
            }
        };
        volleryUtil.setRequestMethod(1);
        volleryUtil.setShow(true);
        volleryUtil.setHeaders("appVersion", getAppVersion());
        volleryUtil.setHeaders("client", "android");
//		volleryUtil.setHeaders("deviceToken", getdeviceId());
        volleryUtil.setHeaders("deviceToken", getdevice_token());
//
//
        volleryUtil.setHeaders("deviceId", getdeviceId());
        volleryUtil.setHeaders("mobileType", getDeviceType());
        volleryUtil.execute(Message_Login.this, Constant.URL
                + "/api/v6/login/app?", params.toString());
    }

    private void initmessage(final int approach) {
        showDialog();
        String capt = et_imgCaptcha.getText().toString();
        AjaxParams params = new AjaxParams();

        params.put("imgCaptcha", capt);
        params.put("approach", approach + "");

        params.put("mobile", tv_user_phone.getText().toString());
        JsonObjectRequest json = new JsonObjectRequest(Method.GET, Constant.URL
                + "/h5/loginCaptcha?" + params.toString(), null,
                new Response.Listener<JSONObject>() {
                    public void onResponse(JSONObject response) {
                        dissmissDialog();
                        if (response.optInt("success") == 1) {
                            Log.e("短信", response.toString());
                            timeCount.start();
                            if (approach == 1) {

                                tv_voice_code.setText("您将会接到电话播报验证码，请保持手机畅通");
                            }
                        } else {

                            initcaptcha();

                            if (!response.optString("comment").equals("")) {

                                ToastUtil.showCenterToast(Message_Login.this,
                                        response.optString("comment"));
                            }

                        }

                    }
                }, new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) {
                dissmissDialog();
            }
        }) {
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("csrf", csrf);
                return headers;
            }
        };
        mQueue.add(json);
    }

}
